package org.dromara.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.system.domain.Department;
import org.dromara.system.domain.Device;
import org.dromara.system.domain.vo.DeviceVo;
import org.dromara.system.mapper.DepartmentMapper;
import org.dromara.system.mapper.DeviceMapper;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.EquipmentBo;
import org.dromara.system.domain.vo.EquipmentVo;
import org.dromara.system.domain.Equipment;
import org.dromara.system.mapper.EquipmentMapper;
import org.dromara.system.service.IEquipmentService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 生产设备Service业务层处理
 *
 * @author Lion Li
 * @date 2025-09-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class EquipmentServiceImpl implements IEquipmentService {

    private final EquipmentMapper baseMapper;

    private final DeviceMapper deviceMapper;

    private final DepartmentMapper departmentMapper;

    /**
     * 查询生产设备
     *
     * @param id 主键
     * @return 生产设备
     */
    @Override
    public EquipmentVo queryById(Long id) {
        EquipmentVo equipmentVo = baseMapper.selectVoById(id);
        if (equipmentVo == null) {
            throw new RuntimeException("该设备不存在");
        }
        // 获取设备所属装置名称
        LambdaQueryWrapper<Device> lqw = Wrappers.lambdaQuery();
        lqw.eq(Device::getId, equipmentVo.getSszz());
        DeviceVo deviceVo = deviceMapper.selectVoOne(lqw);
        Optional.ofNullable(deviceVo).ifPresent(d -> equipmentVo.setSszzmc(d.getSczzmc()));
        // 查询部门
        LambdaQueryWrapper<Department> departmentLqw = Wrappers.lambdaQuery();
        departmentLqw.eq(Department::getId, equipmentVo.getCreateDept());
        Department department = departmentMapper.selectOne(departmentLqw);
        equipmentVo.setCreateDeptName(department != null ? department.getBmmc() : "");
        return equipmentVo;
    }

    /**
     * 分页查询生产设备列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 生产设备分页列表
     */
    @Override
    public TableDataInfo<EquipmentVo> queryPageList(EquipmentBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Equipment> lqw = buildQueryWrapper(bo);
        Page<EquipmentVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (CollectionUtils.isEmpty(result.getRecords())) {
            return TableDataInfo.build(Collections.emptyList());
        }
        Map<Long, String> deptMap = departmentMapper.selectList().stream().collect(Collectors.toMap(Department::getId, Department::getBmmc));
        Map<Long, String> deviceMap = deviceMapper.selectList().stream().collect(Collectors.toMap(Device::getId, Device::getSczzmc));
        result.getRecords().forEach(equipmentVo -> {
            equipmentVo.setSszzmc(deviceMap.getOrDefault(equipmentVo.getSszz(), ""));
            equipmentVo.setCreateDeptName(deptMap.getOrDefault(equipmentVo.getCreateDept(), ""));
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的生产设备列表
     *
     * @param bo 查询条件
     * @return 生产设备列表
     */
    @Override
    public List<EquipmentVo> queryList(EquipmentBo bo) {
        LambdaQueryWrapper<Equipment> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Equipment> buildQueryWrapper(EquipmentBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Equipment> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(Equipment::getId);
        lqw.eq(bo.getSszz() != null, Equipment::getSszz, bo.getSszz());
        lqw.eq(StringUtils.isNotBlank(bo.getSbmc()), Equipment::getSbmc, bo.getSbmc());
        lqw.eq(StringUtils.isNotBlank(bo.getSbwh()), Equipment::getSbwh, bo.getSbwh());
        lqw.eq(StringUtils.isNotBlank(bo.getSbzc()), Equipment::getSbzc, bo.getSbzc());
        lqw.eq(StringUtils.isNotBlank(bo.getSblx()), Equipment::getSblx, bo.getSblx());
        lqw.eq(bo.getTzsbNy() != null, Equipment::getTzsbNy, bo.getTzsbNy());
        lqw.eq(bo.getTzsbfl() != null, Equipment::getTzsbfl, bo.getTzsbfl());
        lqw.eq(bo.getAqfjNy() != null, Equipment::getAqfjNy, bo.getAqfjNy());
        lqw.eq(bo.getAqfjfl() != null, Equipment::getAqfjfl, bo.getAqfjfl());
        lqw.eq(bo.getSbdj() != null, Equipment::getSbdj, bo.getSbdj());
        lqw.eq(bo.getSbzt() != null, Equipment::getSbzt, bo.getSbzt());
        lqw.eq(StringUtils.isNotBlank(bo.getSbxh()), Equipment::getSbxh, bo.getSbxh());
        lqw.eq(bo.getScrq() != null, Equipment::getScrq, bo.getScrq());
        lqw.eq(StringUtils.isNotBlank(bo.getSynx()), Equipment::getSynx, bo.getSynx());
        lqw.eq(StringUtils.isNotBlank(bo.getAzwz()), Equipment::getAzwz, bo.getAzwz());
        lqw.eq(bo.getAzrq() != null, Equipment::getAzrq, bo.getAzrq());
        lqw.eq(bo.getQyrq() != null, Equipment::getQyrq, bo.getQyrq());
        lqw.eq(StringUtils.isNotBlank(bo.getWhbyzq()), Equipment::getWhbyzq, bo.getWhbyzq());
        lqw.eq(StringUtils.isNotBlank(bo.getWhbydw()), Equipment::getWhbydw, bo.getWhbydw());
        lqw.eq(StringUtils.isNotBlank(bo.getZrr()), Equipment::getZrr, bo.getZrr());
        lqw.eq(StringUtils.isNotBlank(bo.getLxfs()), Equipment::getLxfs, bo.getLxfs());
        lqw.eq(Equipment::getDelFlag, 0);
        return lqw;
    }

    /**
     * 新增生产设备
     *
     * @param bo 生产设备
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(EquipmentBo bo) {
        Equipment add = MapstructUtils.convert(bo, Equipment.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改生产设备
     *
     * @param bo 生产设备
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(EquipmentBo bo) {
        Equipment update = MapstructUtils.convert(bo, Equipment.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Equipment entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除生产设备信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
